import React, { useState, forwardRef, useImperativeHandle, useEffect } from 'react';
import {
  EditableProTable, ProTable,
} from '@ant-design/pro-components';
import { Alert, Button, message, Modal, Space, Upload } from "antd";

import TheImage from "@/components/TheImage/index.jsx";
import { apiGoodsStockInfo } from "@/api/marketingTool";
import { apiActivityExcelBlacklistImport } from "../../../../../api/activityManager/index.js";
import Json2Excel from "../../../../../utils/Json2Excel.js";


const Goods = forwardRef((props, ref) => {
  // console.log(props);
  const isProprietary = props.isProprietary
  const selectKeys = props.value.map((item) => item.goodsId);
  const [editableKeys, setEditableRowKeys] = useState(() =>
    props.value.map((item) => item.goodsId),
  );
  const [dataSource, setDataSource] = useState(props.value || []);
  const [selectedRows, setSelectedRows] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [alertType, setAlertType] = useState();
  const [importInfo, setImportInfo] = useState({
    title: '', data: [], message: ''
  });
  const mode = props.mode;
  useImperativeHandle(ref, () => ({
    open, resetData
  }));
  const open = () => {
    setModalOpen(true)
  }
  const resetData = () => {
    // console.log('111')
    setDataSource([])
    setSelectedRows([])
  }
  const columns = [
    {
      title: '商品ID',
      dataIndex: 'goodsId',
      key: 'goodsId',
      editable: false,
      width: 200,
    },
    {
      title: "商品名称",
      dataIndex: "goodsName",
      key: "goodsName",
      ellipsis: true,
      editable: false,
      width: 300,
    },
    {
      title: '商品图片',
      dataIndex: 'goodsShowImages',
      key: 'goodsShowImages',
      editable: false,
      hideInSearch: true,
      width: 500,
      render: (text) => {
        return <TheImage src={text.split(',')} width={80} height={80}></TheImage>
      }
    },
    {
      title: '所属类目',
      dataIndex: 'goodsClassifyName',
      key: 'goodsClassifyName',
      editable: false,
      hideInSearch: true,
      width: 100
    },
    // {
    //     title: '商品原价',
    //     dataIndex: 'originalPrice',
    //     key: 'originalPrice',
    //     valueType: 'money',
    //     hideInSearch: true,
    //     editable: false
    // },
    // {
    //     title: '商品现价',
    //     dataIndex: 'currentPrice',
    //     key: 'currentPrice',
    //     valueType: 'money',
    //     hideInSearch: true,
    //     editable: false
    // },
    {
      title: '商品状态',
      dataIndex: 'goodsStatus',
      key: 'goodsStatus',
      editable: false,
      hideInSearch: true,
      valueEnum: {
        'Y': { text: '上架' },
        'N': { text: '下架' },
      },
      width: 150
    },
    {
      title: '上次操作时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      editable: false,
      hideInSearch: true,
      valueType: 'dateTime',
      width: 150
    },
  ]
  const onAlertClose = () => {
    setAlertType(undefined)
  }
  let tableProps = {}
  if (props.mode === 'view') {
    tableProps = {
      toolBarRender: false
    }
  }
  else {
    tableProps = {
      toolBarRender: (action) => {
        return action.toolBarRender
      }
    }
  }
  // 导出
  const downloadExcel = () => {
    const option = {
      fileName: '活动商品黑名单报错数据',
      header: [
        {
          prop: 'goodsId',
          title: '商品ID(必填)',
        },
        {
          prop: 'goodsName',
          title: '商品名称(非必填)',
        },
        {
          prop: 'checkState',
          title: '校验',
        },
        {
          prop: 'checkMsg',
          title: '说明',
        },
      ],
      dataSource: importInfo.data.map(item => {
        return {
          goodsId: item.goodsId,
          goodsName: item.goodsName,
          checkState: item.checkState,
          checkMsg: item.checkMsg,
        }
      })
    }
    Json2Excel(option)
  }
  // 导入
  const uploadProps = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    onChange: (info) => {
      if (info.file.status === 'done') {
        // message.success('上传成功');
      }
      if (info.file.status === 'error') {
        message.error('上传失败');
      }
    },
    customRequest: async (option) => {
      // console.log("option:", option);
      let params = {
        file: option.file,
      }
      let res = await apiActivityExcelBlacklistImport(params)
      // console.log(res)
      if (res.code === 0) {
        if (res.data.code === 0) {
          const keys = res.data.data.map(item => item.goodsId)
          setEditableRowKeys(keys)
          setSelectedRows(res.data.data)
          setDataSource(res.data.data)
          setAlertType('success')
          setImportInfo({
            title: '导入成功！',
            data: res.data.data,
            message: res.data.codeMessage
          })
          props.onValuesChange(res.data.data)
        } else {
          setAlertType('error')
          setImportInfo({
            title: '导入失败！',
            data: res.data.data,
            message: res.data.codeMessage
          })
        }
      }
      else if (res.code == 5000) {
        setAlertType('error')
        setImportInfo({
          title: '导入失败！',
          data: res.data.data,
          message: res.data.codeMessage
        })
      }
    }
  }
  useEffect(()=>{
    
    if (mode === 'edit'){
        // 处理编辑时回显数据赋值给弹窗默认数据
        setSelectedRows(props.value)
    }
},[])
  return <>
    <Space style={{ marginBottom: 20 }}>
      <Button
        key="new"
        onClick={() => {
          setModalOpen(true)
        }}
      >
        选择商品
      </Button>
      {isProprietary === "Y" && <><Upload {...uploadProps}>
        <Button
          key="into"
        >
          批量导入
        </Button>
      </Upload>
        <Button
          key="down"
          type={'link'}
          href={'https://hqmimage.oss-cn-beijing.aliyuncs.com/%E6%B4%BB%E5%8A%A8%E9%BB%91%E5%90%8D%E5%8D%95%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'}
        >
          下载导入文件模板
        </Button></>}
    </Space>
    <EditableProTable
      rowKey="goodsId"
      bordered={true}
      scroll={{ x: 960, y: '500px' }}
      toolBarRender={false}
      columns={[...columns, {
        title: '操作',
        valueType: 'option',
        width: 250,
        fixed: "right",
        hideInTable: props.mode === 'view',
        render: () => {
          return null;
        },
      }]}
      recordCreatorProps={false}
      value={dataSource}
      controlled={true}
      onChange={props.onValuesChange}
      editable={{
        type: 'multiple',
        editableKeys,
        onChange: setEditableRowKeys,
        actionRender: (row, _, dom) => {
          return <Space style={{ margin: "0 auto" }}>{[dom.delete]}</Space>;
        },
        onValuesChange: (record, recordList) => {
          setDataSource(recordList);
        },
      }}
      pagination={{
        defaultPageSize: 5
      }}
    />
    <Modal
      title={'选择商品'}
      width={'80%'}
      open={modalOpen}
      destroyOnClose={true}
      onOk={() => {
        // console.log(selectedRows);
        setDataSource(selectedRows)
        setEditableRowKeys(selectedRows.map((item) => item.goodsId))
        props.onValuesChange(selectedRows)
        setModalOpen(false)
      }}
      onCancel={() => setModalOpen(false)}
    >
      <ProTable
        bordered={true}
        options={false}
        scroll={{ x: 960, y: '57vh' }}
        rowKey={(record) => record.goodsId}
        columns={columns}
        params={{
          storeStatus: 'Y',
          goodsStatus: 'Y',
          reviewStatus: 'T',
        }}
        request={async (params, sort, filter) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const res = await apiGoodsStockInfo({
            pageNo: params.current,
            pageSize: params.pageSize,
            ...params
          });
          return {
            data: res.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: res.code === 0,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: res.totalCount,
          };
        }}
        pagination={{
          defaultPageSize: 10
        }}
        rowSelection={{
          defaultSelectedRowKeys: selectKeys,
          preserveSelectedRowKeys: true,
          // type: props.type === 'single'?'radio':'checkbox',
          onChange: (keys, rows) => {
            setSelectedRows((prev) => {
              let arr = []
              // 处理跨页勾选值问题
              rows.forEach((item, index) => {
                if (item === undefined) {
                  arr.push(prev.find(v => v.goodsId === keys[index]))
                }
                else {
                  arr.push(item)
                }
              })
              return arr;
            });
          }
        }}
        search={{
          optionRender: (searchConfig, formProps, dom) => {
            return dom.reverse()
          }
        }}
      />
    </Modal>
    {
      alertType && <div style={{ width: '50vw', position: 'fixed', left: "25vw", top: 80, zIndex: 9999 }}>
        <Alert
          banner
          message={importInfo.title}
          showIcon
          description={importInfo.message}
          type={alertType}
          closable
          onClose={() => onAlertClose()}
          action={
            alertType === 'error' && <Space direction="vertical">
              <Button size="small" type="primary" onClick={downloadExcel}>
                下载文件
              </Button>
            </Space>
          }
        />
      </div>
    }

  </>
});

export default Goods;
